package org.apache.flink.connector.httptm.factories;

import org.apache.flink.connector.httptm.HttpTools;
import org.apache.flink.connector.httptm.RequestInfo;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.JsonNode;
import org.apache.flink.shaded.jackson2.com.fasterxml.jackson.databind.ObjectMapper;

import java.net.URI;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 众兴网请求
 */
public class DongbuRequestFactory implements RequestFactory {
    private final ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public String factoryIdentifier() {
        return "zhongxing";
    }

    @Override
    public RequestInfo createRequestInfo(String path, Map<String, String> headers, Map<String, String> params, String body,  Map<String, Object> settings) throws Exception {
        Date curr = new Date();
        Date yest = getYest();
        Map<String, String> format = new HashMap<>();
        format.put("currDay", new SimpleDateFormat("yyyyMMdd").format(curr));
        format.put("yestDay", new SimpleDateFormat("yyyyMMdd").format(yest));
        RequestInfo requestInfo = new RequestInfo(path, format);
        requestInfo.setHeaders(headers);
        requestInfo.setQueryParams(params);
        requestInfo.setBody(body);

        String username = (String) settings.get("username");
        String password = (String) settings.get("password");
        // 这里直接设置, 如果是流式作业, token应该需要设置有效期的刷新机制
        // token有效时间为3小时，若 超时失效，请重新获取;
        requestInfo.setHeader("token", getToken(path, username, password));
        return requestInfo;
    }

    private Date getYest() {
        Calendar yest = Calendar.getInstance();
        yest.setTime(new Date());
        yest.add(Calendar.DATE, -1);
        return yest.getTime();
    }

    /**
     * 获取token
     * @param path url
     * @param username 用户名
     * @param password 密码
     * @return token
     * @throws Exception 异常
     */
    public String getToken(String path, String username, String password) throws Exception {
        HashMap<Object, Object> bodyMap = new HashMap<>();
        bodyMap.put("username", username);
        bodyMap.put("password", password);
        String body = objectMapper.writeValueAsString(bodyMap);
        byte[] result = HttpTools.httpRequest(new URI(path), "POST", new HashMap<>(), body.getBytes(StandardCharsets.UTF_8), 10000, 10000);
        JsonNode jsonNode = objectMapper.readTree(result);
        return jsonNode.get("data").get("token").asText();
    }
}
